#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
创建语言到语音的映射，按照指定的优先级顺序排序
优先级顺序（从高到低）：larynx, glow-speak, coqui-tts, festival, flite, nanotts, marytts, espeak
"""

import json
import argparse

# 定义TTS引擎优先级
TTS_PRIORITY = {
    "larynx": 1,
    "glow-speak": 2,
    "coqui-tts": 3,
    "festival": 4,
    "flite": 5,
    "nanotts": 6,
    "marytts": 7,
    "espeak": 8
}

def load_voices():
    """
    从JSON字符串加载语音数据
    这里直接硬编码了JSON数据，也可以从文件读取
    """
    # 这里应该是从opentts-接口使用.md文件中提取的JSON数据
    # 为简化代码，这里直接使用字符串形式
    with open("opentts-接口使用.md", "r", encoding="utf-8") as f:
        content = f.read()
        # 提取JSON部分
        json_start = content.find('{')
        json_end = content.find('```\n# GET /api/languages')
        json_str = content[json_start:json_end].strip()
        return json.loads(json_str)

def build_language_voice_mapping(save_json=True):
    """
    构建语言到语音的映射，按照TTS引擎优先级排序
    """
    voices_data = load_voices()
    
    # 创建语言到语音的映射
    language_voice_map = {}
    
    for voice_id, voice_info in voices_data.items():
        language = voice_info.get("language")
        tts_name = voice_info.get("tts_name")
        
        if not language or not tts_name:
            continue
        
        # 如果这个语言还没有在映射中，添加它
        if language not in language_voice_map:
            language_voice_map[language] = []
        
        # 添加这个语音到对应语言的列表中
        language_voice_map[language].append({
            "voice_id": voice_id,
            "tts_name": tts_name,
            "priority": TTS_PRIORITY.get(tts_name, 999)  # 如果找不到优先级，给一个很大的数
        })
    
    # 对每种语言的语音按优先级排序
    for language, voices in language_voice_map.items():
        language_voice_map[language] = sorted(voices, key=lambda x: x["priority"])
    if save_json:
        with open("language_voice_mapping.json", 'w', encoding='utf-8') as f:
            json.dump(language_voice_map, f, ensure_ascii=False, indent=2)
        print("已保存语言到语音的映射到文件: language_voice_mapping.json")
    return language_voice_map

def get_best_voice_for_language(language, language_voice_map, save_to_json=True):
    """
    获取指定语言的最佳语音（优先级最高的）
    
    Args:
        language: 语言代码
        language_voice_map: 语言到语音的映射
        save_to_json: 是否将结果保存到JSON文件，默认为True
        
    Returns:
        最佳语音ID或None（如果没有找到）
    """
    best_voice = None
    if language in language_voice_map and language_voice_map[language]:
        best_voice = language_voice_map[language][0]["voice_id"]
        
    if save_to_json and best_voice:
        # 保存到JSON文件
        result = {language: best_voice}
        filename = f"best_voice_{language}.json"
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)
        print(f"已保存最佳语音到文件: {filename}")
        
    return best_voice

def main():
    """
    主函数
    """
    language_voice_map = build_language_voice_mapping()
    # # 
    # # 创建最终的语言到最佳语音的映射
    # best_voices = {}
    # for language, voices in language_voice_map.items():
    #     if voices:  # 确保有可用的语音
    #         best_voices[language] = voices[0]["voice_id"]
    
    # # 保存所有语言的最佳语音到一个JSON文件
    # with open("best_voices_all_languages.json", 'w', encoding='utf-8') as f:
    #     json.dump(best_voices, f, ensure_ascii=False, indent=2)
    # print("已保存所有语言的最佳语音到文件: best_voices_all_languages.json")
    
    # # 输出结果
    # print("\n语言到最佳语音的映射:")
    # for language, voice_id in sorted(best_voices.items()):
    #     print(f"{language}: {voice_id}")
    
    # # 输出每种语言可用的所有语音（按优先级排序）
    # print("\n每种语言的所有可用语音（按优先级排序）:")
    # for language, voices in sorted(language_voice_map.items()):
    #     print(f"{language}:")
    #     for voice in voices:
    #         print(f"  - {voice['voice_id']} (引擎: {voice['tts_name']}, 优先级: {voice['priority']})")
    
    # # 示例：获取特定语言的最佳语音
    # print("\n示例 - 获取中文(zh)的最佳语音:")
    # zh_best_voice = get_best_voice_for_language("zh", language_voice_map, save_to_json=True)
    # print(f"中文(zh)的最佳语音: {zh_best_voice}")

if __name__ == "__main__":
    main()